package com.ztesoft.ossup.report.web;

import static com.ztesoft.ossup.report.dao.ReportRepository.ReportSpecifications.likeReportName;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.ztesoft.ossup.report.dao.ReportRepository;
import com.ztesoft.ossup.report.dao.ReportSubRepo;
import com.ztesoft.ossup.report.domain.Report;
import com.ztesoft.ossup.report.domain.ReportSub;
import com.ztesoft.ossup.report.service.ReportConfigService;
import com.ztesoft.ossup.report.service.ReportListService;


/**
 * Created by luxiang on 16/9/21.
 */
@Controller
@RequestMapping("/report/config")
public class ConfigController extends BaseController {

	@Autowired
	ReportRepository reportRepository;

	@Autowired
	ReportSubRepo reportSubRepo;

	@Autowired
	ReportConfigService reportConfigService;

	@Autowired
	JdbcTemplate jdbcTemplate;

	@Autowired
	ApplicationContext applicationContext;
	
	@Autowired
	ReportListService reportListService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String config() {
		return "/config/list";
	}

	@RequestMapping(value = "/toAddConfig", method = RequestMethod.GET)
	public String toAddConfig(HttpServletRequest request) {
		request.setAttribute("reportConfig", null);
		return "/config/reportConfig";
	}

	@RequestMapping(value = "/toEditConfig/{id}", method = RequestMethod.GET)
	public String toEditConfig(@PathVariable Long id, HttpServletRequest request) {
		Report report = reportRepository.findOne(id);
		List<ReportSub> reportSubs = reportSubRepo.findAllByReportId(id);
		request.setAttribute("reportSubs", reportSubs);
		request.setAttribute("reportConfig", report);
		return "/config/reportConfig";
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public BaseController.PageData<Report> list(@RequestParam(value = "offset") Integer offset,
			@RequestParam(value = "limit") Integer limit, @RequestParam(value = "order", required = false) String order,
			@RequestParam(value = "sort", required = false) String sort,
			@RequestParam(value = "search", required = false) String name) {

		List list = jdbcTemplate.queryForList("select * from report");

		System.out.println(list);

		Page<Report> pages = reportRepository.findAll(Specifications.where(likeReportName(name)), new PageRequest(
				offset / limit, limit, sort != null ? new Sort(Sort.Direction.fromString(order), sort) : null));

		if (pages != null) {
			_logger.debug("pages size:" + pages.getTotalElements());
			List<Report> reports = pages.getContent();
			for(int i = 0;i<reports.size();i++){
				Report report = reports.get(i);
				String state = report.getState();
				String isSum = report.getIsSum();
				Date date = report.getStateDate();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
				String stateDate = dateFormat.format(date);
				//状态值 10A正常 10X失效	
				if("10A".equals(state)){
					pages.getContent().get(i).setState(getI18NMessage("state.normal"));
					
				}else if("10X".equals(state)){
					pages.getContent().get(i).setState(getI18NMessage("state.invalid"));
				}
				//是否总计1表示是 0表示不是
				if("1".equals(isSum)){
					pages.getContent().get(i).setIsSum(getI18NMessage("common.yes"));
				}else if("0".equals(isSum)){
					pages.getContent().get(i).setIsSum(getI18NMessage("common.no"));
				}
				//时间转换
//				if (stateDate != null && !stateDate.equals("")){
//					pages.getContent().get(i).setStateDate(stateDate.substring(0, 19));
//				}
				try {
					pages.getContent().get(i).setStateDate(dateFormat.parse(stateDate));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return new BaseController.PageData<>(pages.getTotalElements(), pages.getContent());
		} else {
			return new BaseController.PageData<>(0l, new ArrayList<Report>());
		}
	}

	@RequestMapping(value = "/test", method = RequestMethod.POST)
	@ResponseBody
	public String test(@RequestBody Map<String, Object> map) {
		System.out.println(map);
		return "test";
	}

	@RequestMapping(value = "/addConfig", method = RequestMethod.POST)
	@ResponseBody
	public String addConfig(@RequestBody Map<String, Object> map) {
		// 提交数据
		// {reportName=2016年度财务报表, reportCode=201600001234, isSum=1,
		// reportType=[101|$|曲线图,102|$|柱状图], reportSelectSql=select * from
		// report}
		Report result=null;
		try {
			result = reportConfigService.saveReport(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result=null;
		}
		ResponseEntry responseEntry = new ResponseEntry(SUCCESS);
		if (result==null) {
			responseEntry.setCode(FAIL);
		}
		Map<String, Object> detail=new HashMap<>();
		detail.put("report", result);
		responseEntry.detail=detail;
		return responseEntry.getJSON();
	}
	

	@RequestMapping(value = "/updateConfig/{id}", method = RequestMethod.POST)
	@ResponseBody
	public String updateConfig(@RequestBody Map<String, Object> map,@PathVariable String id) {
		// 提交数据
		// {reportName=2016年度财务报表, reportCode=201600001234, isSum=1,
		// reportType=[101|$|曲线图,102|$|柱状图], reportSelectSql=select * from
		// report}
		Report result=null;
		String reportId = id.replaceAll(",", "");
		try {
			result = reportConfigService.updateConfig(map, Long.valueOf(reportId));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result=null;
		}
		ResponseEntry responseEntry = new ResponseEntry(SUCCESS);
		if (result==null) {
			responseEntry.setCode(FAIL);
		}
		Map<String, Object> detail=new HashMap<>();
		detail.put("report", result);
		responseEntry.detail=detail;
		return responseEntry.getJSON();
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/checkConfigCodeUnique", method = RequestMethod.POST)
	@ResponseBody
	public String checkConfigCodeUnique(@RequestBody String paramStr) {
		paramStr=paramStr.replace("&", "\",\"");
		paramStr=paramStr.replace("=", "\":\"");
		paramStr="{\""+paramStr+"\"}";
		Map<String, Object> result=new HashMap<>();
		try {
			Map<String, String> params= new Gson().fromJson(paramStr, Map.class);
			boolean b=reportConfigService.isExistConfigCode(params);
			result.put("valid", !b);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.put("valid", false);
		}
		return new Gson().toJson(result);
	}

	@RequestMapping(value = "/checkSql", method = RequestMethod.POST)
	@ResponseBody
	public String checkSql(@RequestBody String sql) {
		sql=sql.replaceAll("\\+", " ");
		try {
			sql=URLDecoder.decode(new String(sql.getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Map<String, Object> result=new HashMap<>();
		try {
//			boolean b = reportConfigService.isSqlRight(sql.substring(4,sql.length()));
			boolean b = reportConfigService.checkSql(sql.substring(4,sql.length()));
			result.put("valid", b);
		} catch (Exception e) {
			// TODO: handle exception
			result.put("valid", false);
		}
		return new Gson().toJson(result);
	}
	@RequestMapping(value = "/deleteConfigByIds", method = RequestMethod.POST)
	@ResponseBody
	public String deleteConfig(@RequestBody String ids) {
		boolean result=false;
		try {
			ids = ids.substring(1, ids.length()-1);
			List<Report> configIds = new ArrayList<Report>();
			String[] idsArray = ids.split(",");
			for(int i = 0;i<idsArray.length ;i++){
				String id = idsArray[i];
				Report report = new Report();
				report.setId(Long.parseLong(id));
				configIds.add(report);
			}
			reportListService.deleteReportCascade(configIds);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			result=false;
		}
		ResponseEntry responseEntry = new ResponseEntry(SUCCESS);
		if (!result) {
			responseEntry.setCode(FAIL);
		}
		return responseEntry.getJSON();
		
	}
}
